package com.cn.jdia.dc.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.jdia.dc.context.SpringContextUtils;
import com.cn.jdia.dc.model.Dbconfig;
import com.cn.jdia.dc.service.IDbconfigService;
import com.cn.jdia.dc.utils.db.DBManager4Mysql;
import com.cn.jdia.dc.utils.db.DBManager4Oracle;

@Controller
@RequestMapping("/dbconfig")
public class DbConfigController {

	@Resource
	private IDbconfigService dbconfigservice;

	@RequestMapping(value = "/test")
	@ResponseBody
	public String dbConnectTest(@RequestParam("ip") String ip, @RequestParam("port") String port,
			@RequestParam("dbtype") String dbtype, @RequestParam("username") String name,
			@RequestParam("password") String pwd, @RequestParam("sid") String sid) {

		System.out.println(ip + " , " + port + " ," + dbtype + "," + name + "," + pwd);

		String url = null;
		int ret = -1;

		if (dbtype.equals("MySql")) {
			url = "jdbc:mysql://" + ip + ":" + port + "/";
			System.out.println(url);

			DBManager4Mysql db = DBManager4Mysql.createInstance();
			ret = db.connectDB(url, name, pwd);
			System.out.println("testRet: " + ret);
			db.closeDB();
		} else if ("Oracle".equals(dbtype)) {
			url = "jdbc:oracle:thin:@" + ip + ":" + port + "/" + sid;
			System.out.println(url);

			DBManager4Oracle db = DBManager4Oracle.createInstance();
			ret = db.connectDB(url, name, pwd);
			System.out.println("testRet: " + ret);
			db.closeDB();
		}

		return ret + "";
	}

	@RequestMapping(value = "/insert")
	@ResponseBody
	public String dbconfigInsert(@RequestParam("sname") String sname, @RequestParam("ip") String ip,
			@RequestParam("port") String port, @RequestParam("dbtype") String dbtype,
			@RequestParam("username") String name, @RequestParam("password") String pwd,
			@RequestParam("defaultdb") String defaultdb, @RequestParam("sid") String sid) {

		int ret = -1;
		System.out.println(sname + "," + ip + " , " + port + " ," + dbtype + "," + name + "," + pwd);

		Dbconfig config = new Dbconfig();
		config.setServername(sname);
		config.setIp(ip);
		config.setPort(port);
		config.setDbtype(dbtype);
		config.setUser(name);
		config.setPwd(pwd);
		config.setDefaultdb(defaultdb);
		config.setSid(sid);

		dbconfigservice = (IDbconfigService) SpringContextUtils.getContext().getBean("dbconfigService");
		ret = dbconfigservice.addDbConfig(config);
		System.out.println("insertRet:" + ret);

		return ret + "";
	}

}
